import 'dart:math' as math;
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:hixing_app/utils/export_utils.dart';
import 'package:hixing_app/views/test_view/canvas_utils.dart';
import 'package:hixing_app/views/test_view/test_matrix4/rect_element_model.dart';

class TestAngle extends StatefulWidget {
  @override
  TestAngleState createState() => TestAngleState();
}

class TestAngleState extends State<TestAngle> {
  CanvasEventType? eventType;

  Offset original = const Offset(200, 200);
  ValueNotifier<double> angleValue = ValueNotifier(0);
  double oldAngle = 0;
  double initialAngle = 0;
  ValueNotifier<Rect> tapRectValue = ValueNotifier(Rect.zero);

  double _calculateAngle(Offset origin, Offset position) {
    final double dx = position.dx - origin.dx;
    final double dy = position.dy - origin.dy;
    return math.atan2(dy, dx);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('原点与触摸点的角度'),
      ),
      body: Listener(
        onPointerDown: (detail) {
          print(tapRectValue.value);
          if (tapRectValue.value.contains(detail.localPosition)) {
            eventType = CanvasEventType.rotate;
          }
          // 记录手指按下时的初始角度
          initialAngle = _calculateAngle(original, detail.localPosition);
        },
        onPointerMove: (detail) {
          if (eventType == CanvasEventType.rotate) {
            print(tapRectValue.value);

            /// 旋转时，先把上一次储存的角度加回来，然后把手势第一下点击的角度抵消掉，就可以解决第一次的时候会旋转一次的问题
            var angle =
                _calculateAngle(Offset.zero, detail.localPosition - original);
            angleValue.value = oldAngle + (angle - initialAngle);
            print(angle);
          }
        },
        onPointerUp: (detail) {
          oldAngle = angleValue.value;
          eventType = null;
        },
        child: CustomPaint(
          size: Size(
            ScreenUI.width,
            ScreenUI.height,
          ),
          painter:
              MyPainter(angleValue: angleValue, tapRectValue: tapRectValue),
        ),
      ),
    );
  }
}

class MyPainter extends CustomPainter {
  MyPainter({required this.angleValue, required this.tapRectValue})
      : super(repaint: angleValue);

  ValueNotifier<double> angleValue;
  ValueNotifier<Rect> tapRectValue;

  @override
  void paint(Canvas canvas, Size size) {
    canvas.save();
    canvas.translate(200, 200);
    canvas.rotate(angleValue.value);
    canvas.translate(-200, -200);
    canvas.drawRect(
        Rect.fromCenter(
            center: const Offset(200, 200), width: 100, height: 100),
        Paint()
          ..color = Colors.red
          ..strokeWidth = 10);
    canvas.restore();

    Matrix4 matrix4 = Matrix4.identity()..rotateZ(angleValue.value);
    // 计算四个顶点的当前位置
    List<Offset> vertex = CanvasUtils.getVertex(
        imgSize: Size(100, 100), matrix: matrix4, useCenterPoint: true);
    Path rotatePath = Path()..moveTo(0, 0);
    rotatePath
      ..relativeLineTo(30, 0)
      ..relativeLineTo(0, -30)
      ..relativeLineTo(-30, 0);
    rotatePath.close();
    canvas.save();
    rotatePath = rotatePath.transform(matrix4.storage);
    rotatePath =
        rotatePath.shift(Offset(150 + vertex[0].dx, 150 + vertex[0].dy));

    canvas.drawPath(rotatePath, Paint()..color = Colors.black);
    tapRectValue.value = rotatePath.getBounds();
    canvas.restore();
  }

  @override
  bool shouldRepaint(covariant MyPainter oldDelegate) {
    // TODO: implement shouldRepaint
    return oldDelegate.angleValue.value != angleValue.value;
  }
}
